# -*- coding: utf-8 -*-
from wbhttp import HttpClient
import json
import re
from logger import logger
from weibo import Weibo


class WeiboSender(Weibo):
    def send_weibo(self, text, img=None):
        url = 'https://m.weibo.cn/api/statuses/update'
        headers = {
            'Origin': 'https://m.weibo.cn/',
            'Referer': 'https://m.weibo.cn/compose'
        }
        data = {
            'content': text,
            'st': self.get_st(),
        }
        if img != None:
            picId = self.upload_pic_path(img)
            if picId != None:
                data['picId'] = picId

        resp = HttpClient.post(url, data=data, headers=headers)
        if resp.status_code == 200 and resp.json()['ok'] == 1:
            logger.info(u'发表成功：' + 'https://weibo.com/5859772466/' + resp.json()['data']['bid'])
            return 'https://weibo.com/5859772466/' + resp.json()['data']['bid'], resp.json()['data']['mid']
        else:
            logger.info(u'发表失败' + resp.json()['msg'])
            return None, None

    def upload_pic_path(self, path):
        url = "http://picupload.service.weibo.com/interface/pic_upload.php?\
              rotate=0&app=miniblog&s=json&mime=image/jpeg&data=1&wm="
        data = open(path, 'rb').read()
        try:
            resp = HttpClient.post(url, data)
            resp_json = re.search('{.*}}', resp.text).group(0)
            result = json.loads(resp_json)
            code = result["code"]
            if code == "A00006":
                pid = result["data"]["pics"]["pic_1"]["pid"]
                logger.info(u'图片上传成功 http://wx4.sinaimg.cn/large/' + pid + '.jpg')
                return pid
            else:
                logger.warning(u"图片上传失败")
                return None
        except Exception as e:
            logger.warning(u"图片上传失败")
            return None
